package com.zwb.service.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zwb.service.common.MailConstants;
import com.zwb.service.pojo.MailLog;
import com.zwb.service.service.IMailLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;

/**
 * @author 头发又黑又长
 * @Date 2022/9/10 23:32
 * @email zwb15083976291@163.com
 */


/* 消息回调 */
@Slf4j
@Component
public class MailCallback implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnsCallback {

    @Autowired(required = false)
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private IMailLogService mailLogService;

    @PostConstruct
    public void init() {
        // 注册到当前 rabbitTemplate 中去
        rabbitTemplate.setMandatory(true);

        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
    }

    /**
     * 消息确认发布
     *
     * @param correlationData 生产者 生产消息携带的id
     * @param ack             确认结果
     * @param cause           失败原因
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        String id = correlationData.getId();
        if (ack) {
            /*消息发送成功*/
            LambdaUpdateWrapper<MailLog> updateWrapper = new LambdaUpdateWrapper<MailLog>()
                    .eq(MailLog::getMsgId, id)
                    .set(MailLog::getStatus, MailConstants.SUCCESS)
                    .set(MailLog::getUpdateTime, new Date());
            mailLogService.update(updateWrapper);
            log.info("消息投递成功=========================:{}", id);
        } else {
            log.error("消息投递失败========================:{}", id);
        }
    }

    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        log.error("交换机为：{},返回消息为:{},路由键为:{},回应消息为:{},回应代码为:{}",
                returnedMessage.getExchange(), returnedMessage.getMessage(),
                returnedMessage.getRoutingKey()
                , returnedMessage.getReplyText()
                , returnedMessage.getReplyCode());

    }
}
